<link type="text/css" href="${request.contextPath}/static/oms/iframe/plugins/jeditor/css/jeditor.css" rel="stylesheet" />
<link rel="stylesheet" href="${request.contextPath}/static/oms/iframe/plugins/fileupload/css/jquery.fileupload-ui.css">
<link href="${request.contextPath}/static/oms/iframe/plugins/bootstrap-image-picker/css/image-picker.css"  rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="${request.contextPath}/static/oms/default/plugins/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css">

<div class="row">
	<div class="col-md-12">
		<form id="articleEditForm" class="form-horizontal" action="${request.contextPath}/cms/article/update" method="post" onsubmit="return false">
			<input type="hidden" id="id" name="id" value="${cmsArticle.id}">
			<div class="box-body">
				<div class="form-group">
					<label id="channelIdLabel" for="channelId" class="col-sm-2  control-label required">栏目</label>
					<div class="col-sm-4">
						<div class="input-group">
							<input type="hidden" class="form-control" id="channelId" name="channelId" required value="${cmsArticle.channelId}" >
							<input type="text" class="form-control"  id="channelName" value="" placeholder="选择栏目...">
							<span class="input-group-addon"><i class="glyphicon glyphicon-remove" style="color: #FF0000;" id="channelIdClear"></i></span>
							<div id="channelContent" class="channelContent" style="position: absolute; left: 0px; top: 25px; display: none;z-index: 999999;">
								<ul id="channelTree" class="ztree" style="margin-top: 10px;
																border: 1px solid #d6e0df;
																background: #fbfbfb;
																width: 220px;
																height: 360px;
																overflow-y: scroll;
																overflow-x: auto; -moz-user-select: none;">
								</ul>
							</div>
						</div>
					</div>

					<input type="hidden" id="tagIds" name="tagIds" value="${cmsArticle.tagIds}" required/>
					<label id="tagIdSelect2Label" for="tagIdSelect2" class="col-sm-2  control-label required">标签</label>
					<div class="col-sm-4">
						<select class="form-control" id="tagIdSelect2" multiple="multiple" name="tagIdSelect2" style="width: 100%;" placeholder="选择标签...">
						</select>
					</div>
				</div>
				<div class="form-group">
					<label for="articleUsername" class="col-sm-2 control-label required">用户名</label>
					<div class="col-sm-4">
						<input type="text" class="form-control" name="username" required value="${cmsArticle.username}" id="articleUsername" placeholder="输入用户名...">
					</div>
					<label id="articleCategoryIdsLabel" for="articleCategoryIds" class="col-sm-2  control-label required">分类</label>
					<div class="col-sm-4">
						<div class="input-group">
							<input type="hidden" class="form-control" id="articleCategoryIds" name="articleCategoryIds"  required value="${cmsArticle.articleCategoryIds}" >
							<input type="text" class="form-control"  id="articleCategoryName" value="" placeholder="选择分类..." autocomplete="off">
							<span class="input-group-addon"><i class="glyphicon glyphicon-remove" style="color: #FF0000;" id="articleCategoryClear"></i></span>
							<div id="articleCategoryContent" class="articleCategoryContent" style="position: absolute; left: 0; top: 25px; display: none;z-index: 999999;">
								<ul id="articleCategoryTree" class="ztree" style="margin-top: 10px;
																border: 1px solid #d6e0df;
																background: #fbfbfb;
																width: 220px;
																height: 360px;
																overflow-y: scroll;
																overflow-x: auto; -moz-user-select: none;">
								</ul>
							</div>
						</div>
					</div>
				</div>
				<div class="form-group">
					<label id="articleTitleLabel" for="articleTitle" class="col-sm-2 control-label required">标题</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="title" id="articleTitle" value="${cmsArticle.title}" required placeholder="输入标题...">
					</div>
				</div>
				<div class="form-group">
					<label id="articleShortTitleLabel" for="articleShortTitle" class="col-sm-2 control-label">短标题</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="shortTitle" id="articleShortTitle"  value="${cmsArticle.shortTitle}" placeholder="输入短标题...">
					</div>
				</div>
				<div class="form-group">
					<label id="articleThumbnailLabel" for="articleThumbnail" class="col-sm-2 control-label">缩略图</label>
					<div class="col-sm-7">
						<input type="text" class="form-control" name="thumbnail" id="articleThumbnail" value="${cmsArticle.thumbnail}" readonly placeholder="输入缩略图...">
					</div>
					<div class="col-sm-3">
						<span class="btn btn-success fileinput-button">
							<i class="glyphicon glyphicon-plus"></i>
							<span>选择文件</span>
							<input id="articleThumbnailFileupload"  class="fileinput-button"  type="file" name="file"  data-url="/system/config/file/add?type=1" multiple>
						 </span>
						<button type="button" class="btn btn-primary btn-sm" ><i class="fa fa-save"></i> 站内选择</button>
					</div>
				</div>
				<div class="form-group">
					<label id="articleBannerLabel" class="col-sm-2 control-label" >横幅图</label>
					<div class="col-sm-7">
						<input type="text" class="form-control" name="banner" id="articleBanner" value="${cmsArticle.banner}"  readonly placeholder="输入横幅图...">
					</div>
					<div class="col-sm-3">
						<span class="btn btn-success fileinput-button">
							<i class="glyphicon glyphicon-plus"></i>
							<span>选择文件</span>
							<input id="articleBannerFileupload"  class="fileinput-button"  type="file" name="file"  width="60" data-url="/system/config/file/add?type=1" multiple>
						 </span>
						<button type="button" class="btn btn-primary btn-sm" ><i class="fa fa-save"></i> 站内选择</button>
					</div>
				</div>
				<div class="form-group">
					<label id="articleShortcutIconLabel" for="articleAuthor" class="col-sm-2 control-label">作者</label>
					<div class="col-sm-4">
						<input type="text" class="form-control" name="author" id="articleAuthor" value="${cmsArticle.author}" placeholder="输入作者...">
					</div>
					<label id="articleSourceLabel" class="col-sm-2 control-label" >来源</label>
					<div class="col-sm-4">
						<input type="text" class="form-control" name="source" id="articleSource" value="${cmsArticle.source}" placeholder="输入来源...">
					</div>
				</div>

				<div class="form-group">
					<label id="articleTypeLabel" for="articleType" class="col-sm-2  control-label required">文章类型</label>
					<div class="col-sm-2">
						<select class="form-control" id="articleType"  name="type" value="${cmsArticle.type}"  required style="width: 100%;" placeholder="选择文章类型...">
						</select>
					</div>
				</div>
				<div class="form-group" id="articleSourceLinkDiv" style="display: none;">
					<label id="articleSourceLinkLabel" class="col-sm-2 control-label" >来源链接</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="sourceLink" id="articleSourceLink" value="${cmsArticle.sourceLink}" placeholder="输入来源链接...">
					</div>
				</div>
				<div class="form-group">
					<label id="articleKeywordsLabel" for="articleKeywords" class="col-sm-2 control-label">关键字</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="keywords" id="articleKeywords" value="${cmsArticle.keywords}" placeholder="输入关键字...">
					</div>
				</div>
				<div class="form-group">
					<label id="articleShareCountLabel" for="articleShareCount" class="col-sm-2 control-label">分享次数</label>
					<div class="col-sm-2">
						<input class="form-control" name="shareCount" id="articleShareCount" value="${cmsArticle.shareCount}" type="number" placeholder="分享次数...">
					</div>
					<label id="articleViewCountLabel" for="articleViewCount" class="col-sm-2 control-label">浏览量</label>
					<div class="col-sm-2">
						<input class="form-control" name="viewCount" id="articleViewCount" value="${cmsArticle.viewCount}" type="number" placeholder="浏览量...">
					</div>
					<label id="articleClickCountLabel" for="articleClickCount" class="col-sm-2 control-label">点击量</label>
					<div class="col-sm-2">
						<input class="form-control" name="clickCount" id="articleClickCount" value="${cmsArticle.clickCount}" type="number" placeholder="点击量...">
					</div>
				</div>
				<div class="form-group">
					<label id="articleWeightLabel" for="articleWeight" class="col-sm-2  control-label">权重</label>
					<div class="col-sm-2">
						<input  class="form-control" name="weight" id="articleWeight" value="${cmsArticle.weight}" type="number" placeholder="权重...">
					</div>
					<label id="articlePriorityLabel" for="articlePriority" class="col-sm-2  control-label">优先级</label>
					<div class="col-sm-2">
						<input  class="form-control" name="priority" id="articlePriority" value="${cmsArticle.priority}" type="number" placeholder="优先级...">
					</div>
					<label id="articleStatusLabel" for="articleStatus" class="col-sm-2  control-label required">状态</label>
					<div class="col-sm-2">
						<select class="form-control" id="articleStatus"  name="status" value="${cmsArticle.status}" required style="width: 100%;" placeholder="选择状态...">
						</select>
					</div>
				</div>
				<div class="form-group">
					<label id="articleDescriptionLabel" class="col-sm-2 control-label" >描述</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="description" id="articleDescription"  value="${cmsArticle.description}" placeholder="输入描述...">
					</div>
				</div>
				<div class="form-group">
					<label id="articleContentLabel" class="col-sm-2 control-label" >内容</label>
					<div class="col-sm-10">
						<textarea  name="content" id="articleContent" data-toggle="jeditor" data-upload="/system/config/file/add?type=1"  placeholder="输入内容...">
							${cmsArticle.content}
						</textarea>
					</div>
				</div>
				<div class="form-group">
					<label id="articleRemarkLabel" class="col-sm-2 control-label">备注</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="remark" id="articleRemark"  ${cmsArticle.remark} placeholder="输入备注...">
					</div>
				</div>
				<div class="error-message text-center" >
					<span class="error-icon"></span>
					<span id="error-msg" class="error-msg" ></span>
				</div>
             </div>
			<div class="box-footer">
				<div class="text-center">
               		<button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 更新</button>
               		<button type="button" class="btn btn-default btn-sm" data-dismiss="modal"><i class="fa fa-close"></i> 关闭</button>
				</div>
          	</div>
		</form>
	</div>
</div>
<!-- 配置文件 -->
<script type="text/javascript" src="${request.contextPath}/static/oms/iframe/plugins/jeditor/js/jeditor.js"></script>
<script src="${request.contextPath}/static/oms/iframe/plugins/fileupload/js/vendor/jquery.ui.widget.js"></script>
<script src="${request.contextPath}/static/oms/iframe/plugins/fileupload/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="${request.contextPath}/static/oms/iframe/plugins/bootstrap-image-picker/js/imagePicker.js"></script>
<script type="text/javascript" src="${request.contextPath}/static/oms/default/plugins/zTree/jquery.ztree.all.js"></script>


<script type="text/javascript">

	var setting = {
		data: {
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "parentId",
				rootPId: null
			}
		},
		async: {
			enable: true,
			url:"/cms/channel/treeGrid",
			dataFilter:function (treeId, parentNode, responseData) {
				if (responseData) {
					for(var i =0; i < responseData.length; i++) {
						responseData[i].url = null;
					}
				}
				return responseData;
			}
		},
		callback:{
			onAsyncSuccess:function (event, treeId) {
				var node = $.fn.zTree.getZTreeObj(treeId).getNodeByParam("id", $("#channelId").val());
				if(node){
					$("#channelName").val(node.name);
				}
			},
			onClick :function (event, treeId, treeNode) {
				$("#channelId").val(treeNode.id);
				$("#channelName").val(treeNode.name);
				$('#channelContent').hide();
			}
		}
	};

	var settingArticleCategory = {
		data: {
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "parentId",
				rootPId: null
			}
		},
		async: {
			enable: true,
			url:"/cms/article/category/treeGrid",
			dataFilter:function (treeId, parentNode, responseData) {
				if (responseData) {
					for(var i =0; i < responseData.length; i++) {
						responseData[i].url = null;
					}
				}
				return responseData;
			}
		},
		callback:{
			onAsyncSuccess:function (event, treeId) {
				var node = $.fn.zTree.getZTreeObj(treeId).getNodeByParam("id", $("#articleCategoryIds").val());
				if(node){
					$("#articleCategoryName").val(node.name);
				}
			},
			onClick :function (event, treeId, treeNode) {
				$("#articleCategoryIds").val(treeNode.id);
				$("#articleCategoryName").val(treeNode.name);
				$('#articleCategoryContent').hide();
			}
		}
	};

function ajaxSubmit(form) {
	
	var $form = $(form);
	
	if ($form.length === 1 && $form.validate()) {
        $.ajax({
            type: 'post',
            url: form.action,
            dataType: "json",
            data: $form.serialize()
        }).done(function(result){
            if (result.success) {
                $("#lgModal").modal('hide');
                alertMsg(result.message,"success");
                articleReload();
            } else {
                $form.find(".error-msg").show();
                $form.find(".error-msg").html(result.message);
            }
        });
	}
}

$(function() {
	$.fn.zTree.init($('#channelTree'), setting);

	$("#channelName").on('click',function () {
		$('#channelContent').css("display")==='none'?$('#channelContent').show():$('#channelContent').hide();
	});
	$("#channelContent").mouseleave(function () {
		$('#channelContent').hide();
	});

	$("#channelIdClear").on('click',function () {
		$("#channelId").val("");
		$("#channelName").val("");
	});

	const $articleUsername = $("#articleUsername");

	$articleUsername.on('blur',function () {
		const $this = $(this);
		if($this.val()){
			settingArticleCategory.async.url="/cms/article/category/treeGrid?username="+$this.val();
			$.fn.zTree.init($('#articleCategoryTree'), settingArticleCategory);
		}
	});

	settingArticleCategory.async.url="/cms/article/category/treeGrid?username="+$articleUsername.val();
	$.fn.zTree.init($('#articleCategoryTree'), settingArticleCategory);

	$("#articleCategoryName").on('click',function () {
		$('#articleCategoryContent').css("display")==='none'?$('#articleCategoryContent').show():$('#articleCategoryContent').hide();
	});
	$("#articleCategoryContent").mouseleave(function () {
		$('#articleCategoryContent').hide();
	});

	$("#articleCategoryClear").on('click',function () {
		$("#articleCategoryIds").val("");
		$("#articleCategoryName").val("");
	});

	$.ajax({
		type:"get",
		url:'/cms/tag/list',
		dataType:'json'
	}).done(function(result){
		const o = [];
		$.each(result, function() {
			if(this.id !== undefined && this.id !==''){
				o.push({'id':this.id,'text':this.name});
			}
		});
		$("#tagIdSelect2").select2({
			data:o,
			minimumInputLength : 0,
			placeholder: "请选择...",
			allowClear: true,
			language: "zh-CN",
			theme: "bootstrap"
		}).val($("#tagIds").val().split(",")).trigger("change");
	});

	$("#articleType").on('change',function () {
		if($(this).val()==='1'){
			$("#articleSourceLinkDiv").hide();
		}else{
			$("#articleSourceLinkDiv").show();
		}
	});

	$("#articleType").select2({
		data: ArticleTypeStore,
		theme: "bootstrap"
	}).val('${cmsArticle.type}').trigger("change");





	$('#tagIdSelect2').change(function(){
		var o=document.getElementById('tagIdSelect2').getElementsByTagName('option');
		var all="";
		console.log(o[1]);
		for(var i=0;i<o.length;i++){
			if(o[i].selected){
				all+=o[i].value+",";
			}
		}

		all = all.substr(0, all.length - 1);//去掉末尾的逗号
		$("#tagIds").val(all);//赋值给隐藏的文本框
	});


	$('[data-toggle="jeditor"]').each(function() {

        var $this = $(this)
        var editor = new jeditor($this);
        var uploadUrl = $this.data('upload');
        editor.config.uploadImgUrl= uploadUrl;
        editor.config.hideLinkImg = true;
        editor.config.uploadImgFileName='file';
        editor.config.containerHeight=400;
        editor.config.uploadImgFns = {
            onload:function (resultText, xhr) {
				var resultObj = eval('(' + resultText + ')');
                console.info('上传结束，返回结果为 ' + resultText);
                var editor = this;
                var originalName = editor.uploadImgOriginalName || '';  // 上传图片时，已经将图片的名字存在 editor.uploadImgOriginalName
                var img;
                if (!resultObj.success) {
                    // 提示错误
                    console.warn('上传失败：' + resultObj.message);
                    alert(resultObj.message);
                } else {
                    console.log('上传成功，即将插入编辑区域，结果为：' + resultText);

                    // 将结果插入编辑器
                    img = document.createElement('img');
                    img.onload = function () {
                        var html = '<img src="' + resultObj.data.urlFull + '" alt="' + originalName + '" style="max-width:100%;"/>';
                        editor.command(null, 'insertHtml', html);

                        console.log('已插入图片，地址 ' + resultObj.data.urlFull);
                        img = null;
                    };
                    img.onerror = function () {
                        console.error('使用返回的结果获取图片，发生错误。请确认以下结果是否正确：' + resultObj.data.urlFull);
                        img = null;
                    };
                    img.src = resultObj.data.urlFull;
                }

            }
		};
        editor.create();
    });

    $("#articleStatus").select2({
        data: StatusStore,
        theme: "bootstrap"
    }).val('${cmsArticle.status}').trigger("change");

    $("#articleThumbnail").imageDynamicPicker();
    $("#articleBanner").imageDynamicPicker();

    $("#articleBannerFileupload").fileupload({
        url: "/system/config/file/add",
        autoUpload: true,
        dataType: 'json',
        acceptFileTypes: /\.(jpg|png|gif)$/i, //浏览器支持File API才有效
        maxFileSize: 2097152, //2M，浏览器支持File API才有效
        send: function(e, data){
            alertMsg('上传中...',"success");
        },
        done: function (e, data) {
            alertMsg("上传成功", "success");
            $("#articleBanner").val(data._response.result.data.url);
        },
        fail: function(e, data) {
            alertMsg("上传失败", "success");
        }
    });
    $("#articleThumbnailFileupload").fileupload({
        url: "/system/config/file/add",
        autoUpload: true,
        dataType: 'json',
        acceptFileTypes: /\.(jpg|png|gif)$/i, //浏览器支持File API才有效
        maxFileSize: 2097152, //2M，浏览器支持File API才有效
        send: function(e, data){
            alertMsg('上传中...',"success");
        },
        done: function (e, data) {
            alertMsg("上传成功", "success");
            $("#articleThumbnail").val(data._response.result.data.url);
        },
        fail: function(e, data) {
            alertMsg("上传失败", "success");
        }
    });


	var $articleEditForm = $("#articleEditForm");
	$articleEditForm.validate({
		rules: {
			title: {
				required: true
			},
			channelId: {
				required: true
			},
			tagIds:{
				required: true
			},
			username:{
				required: true
			},
			articleCategoryIds: {
				required: true
			},
			type: {
				required: true
			},
			status:{
				required:true
			}
		},
		messages: {
			title:{
				required:"标题不能为空！"
			},
			channelId:{
				required:"栏目不能为空！"
			},
			tagIds:{
				required:"标签不能为空！"
			},
			username:{
				required:"用户名不能为空！"
			},
			articleCategoryIds: {
				required: "文章分类不能为空！"
			},
			type: {
				required: "文章类型不能为空！"
			},
			status: {
				required: "状态不能为空！"
			}
		},
		submitHandler:ajaxSubmit,
		errorLabelContainer:".error-msg",
		wrapper:"li",
		showErrors:function(errorMap,errorList) {
			if(errorList.length>0){
				$articleEditForm.find(".error-msg").html(errorList[0].message);
			}else{
				$articleEditForm.find(".error-msg").html("");
			}
		},
		onkeyup: false
	});
});
</script>